#!/bin/bash

printenv

# 定义固定端口号
BTM_CHAT_PORT=8822
MCP_MYSQL_PORT=8811
DORIS_INFO_PORT=8833
ORGANIZATION_PORT=8844
BUSINESS_PORT=8085
NGINX_PORT=8889

# 定义日志级别，默认为info
LOG_LEVEL=${LOG_LEVEL:-info}

# 检查必需的环境变量
check_required_vars() {
    missing_vars=""
    
    # MySQL配置检查
    [ -z "$TARGET_DB_URL" ] && missing_vars="$missing_vars TARGET_DB_URL"
    [ -z "$TARGET_DB_USERNAME" ] && missing_vars="$missing_vars TARGET_DB_USERNAME"

    # MySQL配置检查（mcp-server-organization）
    [ -z "$MSO_DB_URL" ] && missing_vars="$missing_vars MSO_DB_URL"
    [ -z "$MSO_DB_USERNAME" ] && missing_vars="$missing_vars MSO_DB_USERNAME"

    # Meilisearch配置检查
    [ -z "$MEILISEARCH_HOST" ] && missing_vars="$missing_vars MEILISEARCH_HOST"
    [ -z "$MEILISEARCH_DB_INFO_INDEX_NAME" ] && missing_vars="$missing_vars MEILISEARCH_DB_INFO_INDEX_NAME"
    [ -z "$MEILISEARCH_API_KEY" ] && missing_vars="$missing_vars MEILISEARCH_API_KEY"
    
    # 模型配置检查
    [ -z "$MODEL_API_KEY" ] && missing_vars="$missing_vars MODEL_API_KEY"
    
    if [ -n "$missing_vars" ]; then
        echo "错误: 以下必需的环境变量未设置:"
        echo "$missing_vars"
        exit 1
    fi
}

# 定义服务健康检查函数
wait_for_service() {
    port="$1"
    service_name="$2"
    max_attempts=30
    attempt=1
    
    echo "等待 $service_name 服务就绪..."
    while ! nc -z localhost "$port"; do
        if [ $attempt -ge $max_attempts ]; then
            echo "错误: $service_name 服务启动超时"
            exit 1
        fi
        echo "等待 $service_name 服务就绪... 尝试 $attempt/$max_attempts"
        sleep 2
        attempt=$((attempt + 1))
    done
    echo "成功: $service_name 服务已就绪"
}

# 检查外部服务是否可访问
check_external_services() {
    echo "检查外部服务连接..."
    
    # 从URL中提取主机和端口
    meilisearch_host=$(echo "$MEILISEARCH_HOST" | sed -E 's#http[s]?://##' | cut -d/ -f1)
    meilisearch_host_name=$(echo "$meilisearch_host" | cut -d: -f1)
    meilisearch_port=$(echo "$meilisearch_host" | cut -d: -f2)
    
    # 检查Meilisearch服务
    if ! nc -z "$meilisearch_host_name" "$meilisearch_port"; then
        echo "错误: 无法连接到Meilisearch服务 ($MEILISEARCH_HOST)"
        exit 1
    fi
    echo "成功: Meilisearch服务可访问"
    
    # 从MySQL URL中提取主机和端口
    mysql_host=$(echo "$TARGET_DB_URL" | sed -E 's#jdbc:mysql://##' | cut -d/ -f1)
    mysql_host_name=$(echo "$mysql_host" | cut -d: -f1)
    mysql_port=$(echo "$mysql_host" | cut -d: -f2)
    
    # 检查MySQL服务
    if ! nc -z "$mysql_host_name" "$mysql_port"; then
        echo "错误: 无法连接到数据库服务A ($mysql_host $mysql_port $mysql_host_name)"
        exit 1
    fi
    echo "成功: 数据库服务A ($mysql_host $mysql_port $mysql_host_name)可访问"
    
    # 从MySQL URL中提取主机和端口
    mysql_host=$(echo "$MSO_DB_URL" | sed -E 's#jdbc:mysql://##' | cut -d/ -f1)
    mysql_host_name=$(echo "$mysql_host" | cut -d: -f1)
    mysql_port=$(echo "$mysql_host" | cut -d: -f2)
    
    # 检查MySQL服务
    if ! nc -z "$mysql_host_name" "$mysql_port"; then
        echo "错误: 无法连接到数据库服务B ($mysql_host $mysql_port $mysql_host_name)"
        exit 1
    fi
    echo "成功: 数据库服务B ($mysql_host $mysql_port $mysql_host_name)可访问"
}

# 创建日志目录
mkdir -p /app/logs

# 检查环境变量
echo "检查环境变量..."
check_required_vars

# 检查外部服务
check_external_services

# 启动nginx
echo "启动 Nginx 服务..."
nginx

# 启动 mcp-server-mysql
echo "启动 mcp-server-mysql 服务..."
MCP_MYSQL_OPTS="$JAVA_OPTS"
if [ -n "$unsafe_db_ip" ]; then
    MCP_MYSQL_OPTS="$MCP_MYSQL_OPTS -Dsystem.safe.reject.db_ip=$unsafe_db_ip"
fi
java "$MCP_MYSQL_OPTS" \
  -DTARGET_DB_URL="$TARGET_DB_URL" \
  -DTARGET_DB_USERNAME="$TARGET_DB_USERNAME" \
  -DTARGET_DB_PASSWORD="$TARGET_DB_PASSWORD" \
  -Dserver.port="$MCP_MYSQL_PORT" \
  -Dlogging.level.root="$LOG_LEVEL" \
  -jar /app/mcp-server-mysql.jar > /app/logs/mcp-server-mysql.log 2>&1 &
wait_for_service "$MCP_MYSQL_PORT" "mcp-server-mysql"

# 启动 extract-doris-info
echo "启动 extract-doris-info 服务..."
java "$JAVA_OPTS" \
  -DTARGET_DB_URL="$TARGET_DB_URL" \
  -DTARGET_DB_USERNAME="$TARGET_DB_USERNAME" \
  -DTARGET_DB_PASSWORD="$TARGET_DB_PASSWORD" \
  -DMEILISEARCH_HOST="$MEILISEARCH_HOST" \
  -DMEILISEARCH_API_KEY="$MEILISEARCH_API_KEY" \
  -DMEILISEARCH_DB_INFO_INDEX_NAME="$MEILISEARCH_DB_INFO_INDEX_NAME" \
  -Dserver.port="$DORIS_INFO_PORT" \
  -Dlogging.level.root="$LOG_LEVEL" \
  -jar /app/extract-doris-info.jar > /app/logs/extract-doris-info.log 2>&1 &
wait_for_service "$DORIS_INFO_PORT" "extract-doris-info"

# 启动 mcp-server-organization
echo "启动 mcp-server-organization 服务..."
java "$JAVA_OPTS" \
  -DMSO_DB_URL="$MSO_DB_URL" \
  -DMSO_DB_USERNAME="$MSO_DB_USERNAME" \
  -DMSO_DB_PASSWORD="$MSO_DB_PASSWORD" \
  -Dserver.port="$ORGANIZATION_PORT" \
  -Dlogging.level.root="$LOG_LEVEL" \
  -jar /app/mcp-server-organization.jar > /app/logs/mcp-server-organization.log 2>&1 &
wait_for_service "$ORGANIZATION_PORT" "mcp-server-organization"

# 启动 mcp-server-business
echo "启动 mcp-server-business 服务..."
java "$JAVA_OPTS" \
  -DMEILI_HOST="$MEILISEARCH_HOST" \
  -DMEILI_API_KEY="$MEILISEARCH_API_KEY" \
  -Dserver.port="$BUSINESS_PORT" \
  -Dlogging.level.root="$LOG_LEVEL" \
  -jar /app/mcp-server-business.jar > /app/logs/mcp-server-business.log 2>&1 &
wait_for_service "$BUSINESS_PORT" "mcp-server-business"

# 最后启动 btm-chat（前台运行）
echo "启动 btm-chat 服务..."
exec java "$JAVA_OPTS" \
  -DMODEL_API_KEY="$MODEL_API_KEY" \
  -DMODEL_BASE_URL="$MODEL_BASE_URL" \
  -DMODEL_NAME="$MODEL_NAME" \
  -DMODEL_TEMPERATURE="$MODEL_TEMPERATURE" \
  -Dserver.port="$BTM_CHAT_PORT" \
  -Dspring.ai.mcp.client.sse.connections.mcp-server-mysql.url="http://localhost:$MCP_MYSQL_PORT" \
  -Dspring.ai.mcp.client.sse.connections.extract-doris-info.url="http://localhost:$DORIS_INFO_PORT" \
  -Dspring.ai.mcp.client.sse.connections.mcp-server-organization.url="http://localhost:$ORGANIZATION_PORT" \
  -Dspring.ai.mcp.client.sse.connections.mcp-server-business.url="http://localhost:$BUSINESS_PORT" \
  -Dlogging.level.root="$LOG_LEVEL" \
  -jar /app/btm-chat.jar